package SV_HTTP_SPLIT;

import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class Fixed {
    @GetMapping("/checked_except")
    public String checkedExcept(HttpServletResponse response, HttpServletRequest request) throws IOException {
        response.sendRedirect(validateNoSvHttpSplitOrThrow(request.getParameter("HIDDEN_URL")));
        return "Response with header using HttpServletResponse";
    }

    @GetMapping("/checked_except")
    public String checkedExcept2(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String hidden_url = request.getParameter("HIDDEN_URL");
        validateNoSvHttpSplitOrThrow(hidden_url);
        response.sendRedirect(hidden_url);
        return "Response with header using HttpServletResponse";
    }

    @GetMapping("/checked_bool")
    public String checkedBool(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String hidden_url = request.getParameter("HIDDEN_URL");
        if (validateNoSvHttpSplit(hidden_url)) {
            response.sendRedirect(validateNoSvHttpSplitOrThrow(hidden_url));
        }else{
            return "do something else";
        }
        return "Response with header using HttpServletResponse";
    }


    private static String validateNoSvHttpSplitOrThrow(String s) throws IllegalArgumentException{
        if (s.contains("\r") || s.contains("\n")){
            throw new IllegalArgumentException("unexpected SV.HTTP_SPLIT hazard");
        }
        return s;
    }

    private static boolean validateNoSvHttpSplit(String s) {
        if (s.contains("\r") || s.contains("\n")){
            return false;
        }
        return true;
    }
}
